package com.heima.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CreateProjectException;
import com.heima.feigns.article.ApAuthorFeign;
import com.heima.feigns.wemedia.WmUserFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.UserConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import com.heima.utils.common.EmptyUtil;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper,ApUserRealname> implements ApUserRealnameService {
    @Autowired
    ApUserRealnameMapper apUserRealnameMapper;
    @Autowired
    ApUserMapper apUserMapper;
    @Autowired
    WmUserFeign wmUserFeign;
    @Autowired
    ApAuthorFeign apAuthorFeign;
    /**
     * 按照状态查询用户认证列表
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult loadListByStatus(AuthDto dto) {
        //1.验证参数是否可用
        if(EmptyUtil.isNullOrEmpty(dto)){
            CreateProjectException.exec(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        dto.checkParam();
        Page<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        IPage<ApUserRealname> pageResult = null;
        if(dto.getStatus()!= null){
            LambdaQueryWrapper<ApUserRealname> wrapper = Wrappers.<ApUserRealname>lambdaQuery().eq(ApUserRealname::getStatus, dto.getStatus());
            pageResult = page(page, wrapper);
        }else {
            pageResult = page(page);
        }
        List<ApUserRealname> list = pageResult.getRecords();
        // 3 返回结果
        PageResponseResult result =  new PageResponseResult(dto.getPage(), dto.getSize(), (int)pageResult.getTotal());
        result.setData(list);
        return result;
    }

    /**
     * 审核通过/不通过
     *
     * @param dto
     * @param status
     * @return
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult authPassOrNo(AuthDto dto, String status) {
        //1。校验参数
        if(EmptyUtil.isNullOrEmpty(dto)||dto.getId()==null||status == null){
            CreateProjectException.exec(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.执行业务
        //2.1防止恶意刷接口 (获取验证用户是否存在)
        ApUserRealname apUserRealname = getOne(Wrappers.<ApUserRealname>lambdaQuery().eq(ApUserRealname::getId, dto.getId())
                .eq(ApUserRealname::getStatus, UserConstants.AP_USER_REALNAME_WAIT_CHECK));
        if(apUserRealname ==null){
           CreateProjectException.exec(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery()
                        .eq(ApUser::getId,apUserRealname.getUserId())
                        .eq(ApUser::getStatus, UserConstants.AP_USER_STATUS_NORMAL));
        if(EmptyUtil.isNullOrEmpty(apUser)){
            CreateProjectException.exec(AppHttpCodeEnum.USER_IS_NOT_EXIT);
        }
        //2.2 修改用户状态
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(Short.valueOf(status));
        apUserRealname.setUpdatedTime(new Date());
        if(dto.getMsg()  != null){
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);
        //2.3 判断用户是通过还是不通过
        if(UserConstants.AP_USER_REALNAME_CHECK_TRUE.equals(Integer.valueOf(status))){
            //2.4 远程调用接口 先验证 再插入
            WmUser wmUser = createWmUser(dto, apUser);
            if(EmptyUtil.isNullOrEmpty(wmUser)){
                CreateProjectException.exec(AppHttpCodeEnum.ADD_WEMEDIA_FAIL);
            }

            Boolean flag = createArticle(wmUser);
            if(!flag){
                CreateProjectException.exec(AppHttpCodeEnum.ADD_APAUTHOR_FAIL);
            }
        }

        apUser.setFlag(Short.valueOf(status));
        apUserMapper.updateById(apUser);
        //3.返回结果
        return  ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private Boolean createArticle(WmUser wmUser) {
        ApAuthor apAuthor = apAuthorFeign.findByUserId(wmUser.getApUserId());
        if(apAuthor == null){
            apAuthor = new ApAuthor();
            apAuthor.setCreatedTime(new Date());
            apAuthor.setName(wmUser.getName());
            apAuthor.setType(2); // 自媒体人类型
            apAuthor.setUserId(wmUser.getApUserId()); // APP 用户ID
            apAuthor.setWmUserId(wmUser.getId()); // 自媒体用户ID
            apAuthorFeign.save(apAuthor);
            return true;
        }
        return false;
    }

    private WmUser createWmUser(AuthDto dto, ApUser apUser) {
        WmUser wmUser = wmUserFeign.findByName(apUser.getName());
        if(wmUser == null){
            WmUser wm = new WmUser();
            wmUser = new WmUser();
            wmUser.setName(apUser.getName());
            wmUser.setSalt(apUser.getSalt());  // 盐
            wmUser.setPassword(apUser.getPassword()); // 密码
            wmUser.setPhone(apUser.getPhone());
            wmUser.setCreatedTime(new Date());
            wmUser.setType(0); // 个人
            wmUser.setApUserId(apUser.getId());  // app端用户id
            wmUser.setStatus(UserConstants.AP_USER_REALNAME_CHECK_TRUE);
            wmUser =  wmUserFeign.save(wmUser);
            if(wmUser.getId() != null){
                return wmUser;
            }
        }
        return null;
    }
}
















